import * as React from "react";
import {
  Row,
  Col,
  Button,
  Modal,
  Spin,
  Table,
  Space,
  Typography,
  Input,
  Select,
  Form,
  InputNumber,
  message,
  Upload,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import { WebVariable } from "../../../../../../data/WebVariable";
import ModalTerminalRedio from "../ModalTerminalRedio";
import ModelBindArgs from "../ModelBindArgs";
import IconFont from "../../../../../../assets/ICON";
import { SearchConditionData } from "../../index";
import {
  exportFile,
  getUserInfo,
  importFile,
} from "../../../../../../utils/common";
import {
  getDeviceManagement,
  Deviceadd,
  getComponentType,
  Devicedelete,
  Devicebinding, //批量绑定
  Deviceunbind, //批量解绑
  getbounddeal, //根据typeID获取绑定参数
  updateDeviceParam,
  downDeviceTemplateUrl,
  importDeviceUrl,
} from "../../../deviceseversapi";
import { ergodicListAddIdToKey } from "../../../../../../utils/common";
const { Text } = Typography;
const { Option } = Select;
export interface DeviceTableProps {
  queryData: SearchConditionData;
}

interface rowDataType {
  terminalId: string;
  id: string;
  name: string;
  energyType: string;
  paraVal: string;
  isLoad: string;
}

export interface DeviceTableState {
  selectedRowKeys: string[];
  selectedRows: rowDataType[];
  loading: boolean;
  visible: boolean;
  bindvisible: boolean;
  bindFromVisible: boolean;
  subItem: any[];
  typeId: string;
  terId: string;
  yibang: string[];
  weibang: string[];
  resultVisible: Boolean;
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
class DeviceTable extends React.Component<DeviceTableProps, DeviceTableState> {
  private columns: columnsDataCLass[] = [
    {
      key: "no",
      title: "装载",
      dataIndex: "no",
      width: 60,
      render: (text, record, index) => {
        let isLoad: any = [];
        if (record.isLoad === "1") {
          isLoad.push(<span style={{ color: "#008000" }}>是</span>);
        } else {
          isLoad.push(<span style={{ color: "#F4990D" }}>否</span>);
        }
        return isLoad;
      },
    },
    {
      key: "name",
      title: "绑定",
      dataIndex: "name",
      width: 60,
      render: (text, record, index) => {
        let isLoad: any = [];
        if (record.paraVal) {
          isLoad.push(<span style={{ color: "#008000" }}>是</span>);
        } else {
          isLoad.push(<span style={{ color: "#F4990D" }}>否</span>);
        }
        return isLoad;
      },
    },
    {
      key: "name",
      title: "设备名称",
      dataIndex: "name",
      width: 150,
    },
    {
      key: "devAddr",
      title: "设备地址",
      dataIndex: "devAddr",
      width: 150,
    },
    {
      key: "typeName",
      title: "分项类型",
      dataIndex: "typeName",
      width: 100,
    },
    {
      key: "energyType",
      title: "能源类型",
      dataIndex: "energyType",
      width: 80,
      render: (text, record, index) => {
        let str = "";
        if (record.energyType === "1") {
          str = "电";
        } else if (record.energyType === "2") {
          str = "水";
        } else if (record.energyType === "3") {
          str = "原煤";
        } else if (record.energyType === "4") {
          str = "原油";
        } else if (record.energyType === "5") {
          str = "天然气";
        } else if (record.energyType === "6") {
          str = "蒸气";
        } else {
          str = "";
        }
        return str;
      },
    },
    // {
    //   key: "ct",
    //   title: "CT",
    //   dataIndex: "ct",
    //   width: 100,
    // },
    // {
    //   key: "pt",
    //   title: "PT",
    //   dataIndex: "pt",
    //   width: 100,
    // },

    {
      key: "terName",
      title: "终端名称",
      dataIndex: "terName",
      width: 100,
    },
    // {
    //   key: "installAddr",
    //   title: "安装地址",
    //   dataIndex: "installAddr",
    //   width: 200,
    // },
    {
      key: "terAddress",
      title: "终端地址",
      dataIndex: "terAddress",
      width: 100,
    },
    {
      key: "cldh",
      title: "测量点号",
      dataIndex: "cldh",
      width: 80,
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      width: 150,
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.Mod = "update";
                  this.onEditDevice(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              {record.terName ? (
                <span
                  style={{ cursor: "pointer" }}
                  onClick={() => {
                    this.BindMod = "Edit";
                    this.attr.id = record.id;
                    this.attr.terminalId = record.terminalId;
                    this.initDeviceValue = record;
                    this.setState({ bindFromVisible: true });
                    this.forceUpdate();
                  }}
                >
                  <IconFont
                    type="icon_form_bangding"
                    style={{ color: "#1890FF" }}
                  />
                  <Text>修改参数</Text>
                </span>
              ) : (
                <span
                  style={{ cursor: "pointer" }}
                  onClick={() => {
                    // this.setState({ selectedRowKeys: [record.id] });
                    this.onBindDevice(record);
                  }}
                >
                  <IconFont
                    type="icon_form_bangding"
                    style={{ color: "#1890FF" }}
                  />
                  <Text>绑定</Text>
                </span>
              )}

              {/* <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onDeleteSimpleDevice(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span> */}
            </Space>
          </>
        );
      },
    },
  ];
  private initDeviceValue: any = null;
  Mod = "add";
  BindMod = "set";
  private dataSouce: any[] = [];
  private pageIndex: number = 1;
  private pageSize: number = 20;
  private total: number = 0;
  private attr: any = {};
  private importResult: [] = [];
  private importColumns: any[] = [
    {
      title: "设备编号",
      dataIndex: "no",
      key: "no",
    },
    {
      title: "设备名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "设备地址",
      dataIndex: "devAddr",
      key: "devAddr",
    },
    {
      title: "能源类型",
      dataIndex: "energyType",
      key: "energyType",
      render: (text, record, index) => {
        let str = "";
        if (record.energyType === "1") {
          str = "电";
        } else if (record.energyType === "2") {
          str = "水";
        } else if (record.energyType === "3") {
          str = "原煤";
        } else if (record.energyType === "4") {
          str = "原油";
        } else if (record.energyType === "5") {
          str = "天然气";
        } else if (record.energyType === "6") {
          str = "蒸气";
        } else {
          str = "";
        }
        return str;
      },
    },
    {
      title: "终端地址",
      dataIndex: "terminalAddr",
      key: "terminalAddr",
    },
    {
      title: "失败原因",
      dataIndex: "msg",
      key: "msg",
      render: (value) => <span style={{ color: "red" }}>{value}</span>,
    },
  ];
  state = {
    selectedRowKeys: [],
    selectedRows: [], //表格选中单行数据
    loading: false,
    visible: false, //新增编辑弹窗
    bindvisible: false, //选择终端弹窗
    bindFromVisible: false, //单个绑定参数
    subItem: [],
    typeId: "",
    terId: "",
    yibang: [],
    weibang: [],
    resultVisible: false,
  };
  private fromAddOrEdit: any = null;
  private visibleCTPT: any = false;
  render() {
    let {
      selectedRowKeys,
      //  selectedRows,
    } = this.state;
    let rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <>
        <div className="rowcon_body">
          <Row>
            <Col span={24} className="subject">
              <div className="operation">
                <Button
                  type="primary"
                  className="increased"
                  size="middle"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    this.onAddDevice();
                  }}
                >
                  新增
                </Button>
                <Button
                  type="primary"
                  className="addoperating"
                  size="middle"
                  icon={<IconFont type="icon_form_shanchu" />}
                  onClick={() => {
                    this.onDeleteBatchDevice();
                  }}
                >
                  删除
                </Button>
                <Button
                  type="primary"
                  className="binding"
                  size="middle"
                  icon={
                    <IconFont type="icon_bangding" style={{ fontSize: 12 }} />
                  }
                  onClick={() => {
                    this.onBindBatchDevice();
                  }}
                >
                  绑定
                </Button>
                <Button
                  type="primary"
                  className="unbundle"
                  size="middle"
                  icon={<IconFont type="icon_form_jiebang" />}
                  onClick={() => {
                    this.onUnBindBatchDevice();
                  }}
                >
                  解绑
                </Button>
                <Button
                  type="primary"
                  className="export"
                  size="middle"
                  onClick={this.DownloadTemplate}
                  icon={<IconFont type="icon_xiazai" />}
                >
                  模板下载
                </Button>
                <Upload
                  accept=".xlsx"
                  showUploadList={false}
                  beforeUpload={(file) => {
                    const formData = new FormData();
                    formData.append("file", file);
                    formData.append("peId", getUserInfo("peId"));
                    importFile(
                      importDeviceUrl,
                      formData,
                      this,
                      (result) => {
                        if (result.success) {
                          if (result.data && result.data.length > 0) {
                            this.importResult = result.data;
                            this.setState({ resultVisible: true });
                            this.getDataList();
                          } else {
                            this.setState({ resultVisible: false });
                          }
                        }
                      },
                      (err) => {
                        this.setState({ resultVisible: false });
                      }
                    );
                    return false;
                  }}
                >
                  <Button
                    type="primary"
                    className="export"
                    size="middle"
                    icon={<IconFont type="icon_daochu" />}
                  >
                    导入
                  </Button>
                </Upload>
              </div>
            </Col>
            <Col span={24}>
              <Spin spinning={this.state.loading}>
                <Table
                  columns={this.columns}
                  dataSource={this.dataSouce}
                  rowSelection={rowSelection}
                  pagination={{
                    pageSize: this.pageSize,
                    total: this.total,
                    current: this.pageIndex,
                    onChange: (page: number) => {
                      this.pageIndex = page;
                      this.getDataList();
                    },
                  }}
                  sticky
                ></Table>
              </Spin>
            </Col>
          </Row>
          <Modal
            title={this.Mod === "add" ? "新增设备" : "编辑设备"}
            visible={this.state.visible}
            width="682px"
            onOk={() => {
              this.handleAddDeviceOk();
            }}
            onCancel={() => {
              this.handleAddDeviceCancel();
            }}
            maskClosable={false}
          >
            <Form {...formItemLayout} ref={(el) => (this.fromAddOrEdit = el)}>
              <Row>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="设备名称："
                    name="name"
                    rules={[
                      {
                        required: true,
                        message: "请填写设备名称",
                      },
                    ]}
                  >
                    <Input placeholder="设备名称" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="设备编号："
                    name="no"
                    rules={[
                      {
                        required: true,
                        message: "请填写设备编号",
                      },
                    ]}
                  >
                    <Input placeholder="设备编号" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="能源类型："
                    name="energyType"
                    rules={[
                      {
                        required: true,
                        message: "请填写能源类型",
                      },
                    ]}
                  >
                    <Select
                      onChange={(key) => {
                        this.visibleCTPT = key === "2";
                        this.forceUpdate();
                      }}
                    >
                      {WebVariable.categoryType.map((item: any) => {
                        return (
                          <Option value={item.key} key={item.key}>
                            {item.label}
                          </Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="设备地址："
                    name="devAddr"
                    rules={[
                      {
                        required: true,
                        message: "请填写设备地址",
                      },
                    ]}
                  >
                    <Input placeholder="设备地址" />
                  </Form.Item>
                </Col>
                {this.visibleCTPT ? null : (
                  <Col span={11} offset={1}>
                    <Form.Item
                      label="CT:"
                      name="ct"
                      rules={[
                        {
                          required: true,
                          message: "请填写电流变比",
                        },
                      ]}
                    >
                      <InputNumber
                        min={1}
                        placeholder="电流变比"
                        style={{ width: "100%" }}
                      />
                    </Form.Item>
                  </Col>
                )}
                {this.visibleCTPT ? null : (
                  <Col span={11} offset={1}>
                    <Form.Item
                      label="PT："
                      name="pt"
                      rules={[
                        {
                          required: true,
                          message: "请填写电压变比",
                        },
                      ]}
                    >
                      <InputNumber
                        min={1}
                        placeholder="电压变比"
                        style={{ width: "100%" }}
                      />
                    </Form.Item>
                  </Col>
                )}

                <Col span={11} offset={1}>
                  <Form.Item label="安装位置：" name="installAddr">
                    <Input placeholder="安装位置" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="分项类型：" name="deviceTypeId">
                    <Select placeholder="请选择分项" style={{ width: "100%" }}>
                      {this.state.subItem.map((province: any) => (
                        <Option key={province.id + ""} value={province.id + ""}>
                          {province.name}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
          <ModalTerminalRedio
            visible={this.state.bindvisible}
            onTerOk={(data: any) => {
              this.setState({
                bindvisible: data.visible,
                typeId: data.typeId,
                terId: data.terId,
              });
              this.attr.typeId = data.typeId;
              this.forceUpdate();
              this.getPreamBindAction(data.terId, data.typeId);
            }}
            onTerCancel={(data: any) => {
              this.setState({ bindvisible: data.visible });
            }}
          ></ModalTerminalRedio>
          <ModelBindArgs
            Mod={this.BindMod}
            attr={this.attr}
            visible={this.state.bindFromVisible}
            onTypeOk={(data: any) => {
              this.onTypeOk(data);
            }}
            onTypeCancel={(data: any) => {
              this.onTypeCancel(data);
            }}
          ></ModelBindArgs>

          {/*---导入结果窗口---*/}
          <Modal
            title="导入失败结果"
            width={1600}
            centered={true}
            visible={this.state.resultVisible}
            okText={"确定"}
            cancelText={"取消"}
            maskClosable={false}
            onCancel={() => {
              this.setState({ resultVisible: false });
            }}
            onOk={() => {
              this.setState({ resultVisible: false });
            }}
          >
            <Table
              bordered={false}
              rowKey={"id"}
              columns={this.importColumns}
              dataSource={this.importResult}
              pagination={false}
              style={{
                height: 600,
                overflowY: "auto",
                width: "100%",
                backgroundColor: "white",
              }}
            />
          </Modal>
        </div>
      </>
    );
  }
  /**钩子函数 */
  componentWillMount() {
    this.agreement();
    this.getDataList();
  }
  shouldComponentUpdate(newProps, newState) {
    if (newProps.queryData !== this.props.queryData) {
      this.getDataList(newProps.queryData);
    }
    return true;
  }
  /**回调方法 */
  onTypeCancel(data) {
    this.setState({ bindFromVisible: data.visible });
  }
  onTypeOk(data) {
    this.setState({ bindFromVisible: data.visible });
    let pream: any = null;
    if (this.BindMod === "set") {
      pream = {
        deviceId: this.initDeviceValue["id"],
        paraVal: data.paraVal,
        terminalId: this.state.terId,
      };
    } else {
      pream = {
        deviceId: this.initDeviceValue["id"],
        paraVal: data.paraVal,
        terminalId: this.attr.terminalId,
      };
    }

    this.updateDevice(pream);
  }
  /**操作 */
  //绑定操作判断
  getPreamBindAction(terId: string, typeId: string) {
    if (this.state.selectedRowKeys.length > 0) {
      switch (this.state.selectedRowKeys.length) {
        case 0:
          message.error("请至少选择一个设备");
          break;

        default:
          //批量绑定逻辑
          this.BindBatchDevice(terId);
          break;
      }
    } else {
      this.BindMod = "set";
      this.setState({ bindFromVisible: true });
      this.forceUpdate();
    }
  }
  onUnBindBatchDevice() {
    let _this = this;
    if (this.state.selectedRowKeys.length > 0) {
      let c = this.state.selectedRowKeys.concat(this.state.weibang);
      let temp = this.state.selectedRows.filter(
        (item: rowDataType) => item.isLoad === "1"
      );
      if (temp.length > 0) {
        message.error("选项中存在档案已装载设备,请先卸载再解绑！");
        return false;
      }
      let bn = this.ifArrRepeat(c); //为true说明选项符合要求，没有未绑定项
      if (bn) {
        Modal.confirm({
          title: "是否确认解绑设备",
          onOk: () => {
            _this.UnBindDevice();
          },
        });
      } else {
        message.error("您的选项中有未绑定的设备");
      }
    } else {
      message.error("请至少选择一个设备");
    }
  }
  //单项绑定
  onBindDevice(record) {
    this.initDeviceValue = record;
    this.setState({ bindvisible: true });
    this.forceUpdate();
  }
  //判断arr是否重复
  ifArrRepeat(arr) {
    let len = arr.length;
    const s = new Set();
    arr.forEach((x) => s.add(x));
    return s.size === len;
  }
  //批量绑定
  onBindBatchDevice() {
    if (this.state.selectedRowKeys.length > 0) {
      let c = this.state.selectedRowKeys.concat(this.state.yibang);
      let temp = this.state.selectedRows.filter(
        (item: rowDataType) => item.isLoad === "1"
      );
      if (temp.length > 0) {
        message.error("选项中存在档案已装载设备！");
        return false;
      }
      let bn = this.ifArrRepeat(c); //为true说明选项符合要求，没有已绑定项
      if (bn) {
        this.setState({ bindvisible: true });
      } else {
        message.error("您的选项中有已绑定的设备");
      }
    } else {
      message.error("请至少选择一个设备");
    }
  }
  //单项删除设备
  onDeleteSimpleDevice(record: any) {
    let _this = this;
    let pream = {
      idList: [record.id],
    };
    let temp = this.state.selectedRows.filter(
      (item: rowDataType) => item.isLoad === "1"
    );
    if (temp.length > 0) {
      message.error("选项中存在档案已装载设备,请先卸载再删除！");
      return false;
    }
    Modal.confirm({
      title: "是否确认删除设备",
      onOk: () => {
        _this.deleteDevice(pream);
      },
    });
  }
  //批量删除设备
  onDeleteBatchDevice() {
    let _this = this;
    if (this.state.selectedRowKeys.length > 0) {
      let pream = {
        idList: this.state.selectedRowKeys,
      };
      let temp = this.state.selectedRows.filter(
        (item: rowDataType) => item.isLoad === "1"
      );
      if (temp.length > 0) {
        message.error("选项中存在档案已装载设备,请先卸载再删除！");
        return false;
      }
      Modal.confirm({
        title: "是否确认删除选中的设备",
        onOk: () => {
          _this.deleteDevice(pream);
        },
      });
    } else {
      message.error("请至少选择一个设备");
    }
  }
  //编辑设备
  onEditDevice(record: any) {
    // this.clearAddDeviceModal();
    this.initDeviceValue = record;
    this.setState({
      visible: true,
    });
    this.forceUpdate();
    if (record) {
      setTimeout(() => {
        if (this.fromAddOrEdit) {
          const container: any = (this.fromAddOrEdit as any) as HTMLDivElement;
          container.setFieldsValue(record);
        }
      });
    }
  }
  //新增设备
  onAddDevice() {
    this.setState({
      visible: true,
    });
  }
  //新增编辑提交
  handleAddDeviceOk() {
    let _this = this;
    const container: any = (this.fromAddOrEdit as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        // _this.ChangeModalVisible();

        _this.setPream(res);
        //清空表单
        _this.clearAddDeviceModal();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  handleAddDeviceCancel() {
    this.clearAddDeviceModal();
  }

  //选择操作的设备
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys: selectedRowKeys,
      selectedRows: selectedRows,
    });
  };
  /**数据请求 */
  //单项绑定修改参数
  async updateDevice(pream) {
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await updateDeviceParam(pream).catch((err) => {
        _this.setState({ loading: false });
        _this.initDeviceValue = null;
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.initDeviceValue = null;
        _this.getDataList();
        _this.clearState();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.initDeviceValue = null;
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }

  //批量解绑设备
  async UnBindDevice() {
    let pream = {
      deviceIds: this.state.selectedRowKeys,
      terId: null,
    };
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await Deviceunbind(pream).catch((err) => {
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.getDataList();
        _this.clearState();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //根据typeId获取绑定参数
  async getBiundCode(typeId: string) {
    //getbounddeal
    let pream = {
      protocolId: typeId,
    };
    let _this = this;
    try {
      let res: any = await getbounddeal(pream).catch((err) => {});
      let json: AjaxData = res;
      if (json.success) {
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {},
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //批量绑定设备
  async BindBatchDevice(terId: string) {
    let pream = {
      deviceIds: this.state.selectedRowKeys,
      terId,
    };
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await Devicebinding(pream).catch((err) => {
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.getDataList();
        _this.clearState();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //删除设备
  async deleteDevice(pream: { idList: string[] }) {
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await Devicedelete(pream).catch((err) => {
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.getDataList();
        _this.clearState();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //新增或编辑设备
  async addOrEditDevice(pream: any) {
    let _this = this;
    try {
      _this.setState({ loading: true });
      debugger;
      let res: any = await Deviceadd(pream).catch((err) => {
        _this.setState({ loading: false });
        _this.initDeviceValue = null;
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.initDeviceValue = null;
        _this.getDataList();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.initDeviceValue = null;
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //获取分页设备列表
  async getDataList(queryData?: SearchConditionData) {
    let _this = this;
    let pream = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      queryData: queryData ? queryData : this.props.queryData,
    };
    try {
      _this.setState({ loading: true });
      let res: any = await getDeviceManagement(pream).catch((err) => {
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.dataSouce = ergodicListAddIdToKey(json.data.records);
        _this.getChangeBindArr(ergodicListAddIdToKey(json.data.records));
        _this.total = json.data.total;
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //获取分项类型下拉
  async agreement() {
    let res: any = await getComponentType().catch((err) => {
      console.log(err);
    });
    const json: any = res;
    if (res) {
      this.setState({
        subItem: json.data,
      });
    }
  }

  /**被动方法，调用函数 */
  //获取选中的设备是否被绑定
  getChangeBindArr(arr: any[]) {
    let yibang: string[] = [];
    let weibang: string[] = [];
    arr.map((item) => {
      if (item.terName) {
        //被绑定
        yibang.push(item.id);
      } else {
        weibang.push(item.id);
      }
      return item;
    });
    this.setState({
      yibang,
      weibang,
    });
  }
  //修改或者新增from表单提交时调用判断是新增还是修改
  setPream(item: any) {
    let _this = this;
    for (let key in item) {
      item[key] = item[key] ? item[key] : null;
    }

    switch (this.Mod) {
      case "add":
        item["isFictitious"] = 0;
        _this.addOrEditDevice(item);
        break;
      case "update":
        item["id"] = this.initDeviceValue["id"];
        _this.addOrEditDevice(item);
        break;
      default:
        break;
    }
  }
  //清空新增编辑弹窗
  clearAddDeviceModal() {
    if (this.fromAddOrEdit) {
      const container: any = (this.fromAddOrEdit as any) as HTMLDivElement;
      container.setFieldsValue({
        name: undefined,
        no: undefined,
        energyType: undefined,
        devAddr: undefined,
        ct: 1,
        pt: 1,
        installAddr: undefined,
        deviceTypeId: undefined,
      });
    }

    this.setState({
      visible: false,
    });
  }
  //清空状态
  clearState() {
    this.setState({ selectedRowKeys: [] });
  }

  DownloadTemplate() {
    exportFile(downDeviceTemplateUrl, "", "设备导入模板.xlsx");
  }
}

export default DeviceTable;
